package network

import (
	"fmt"
	"net"
	"sync/atomic"
)

func newTCPClient(c *net.TCPConn, ts *TCPServer) *TCPClient {
	p := &TCPClient{
		TCPSocket: TCPSocket{
			tCPConn: c,
			guid:    genGuid(),
			//readChan:  ts.readChan,
			writeChan: make(chan *SendPacket, ID_CLIENT_WRITE_CHAN_LENGTH),
		},
		ts: ts,
	}

	ts.connectMap.Store(p.GetGuid(), p)
	socketMap.Store(p.GetGuid(), p)
	atomic.AddInt32(&p.ts.curConnNum, 1)
	p.addPack(ID_MSG_TYPE_CLIENT_NEW_CONNECTION, nil)

	p.run()
	return p
}

func (m *TCPClient) run() {
	m.syncClose.Add(2)
	go m.monitor()
	go m.read()
	go m.write()
}

func (m *TCPClient) monitor() {
	m.syncClose.Wait()
	fmt.Printf("TCPClient:%v monitor end\n", m.GetGuid())

	m.ts.connectMap.Delete(m.GetGuid())
	socketMap.Delete(m.GetGuid())
	atomic.AddInt32(&m.ts.curConnNum, -1)
	m.addPack(ID_MSG_TYPE_CLIENT_DISCONNECTION, nil)
}
